package com.kstech.ks_gaz01.fragments

import android.view.View
import androidx.appcompat.app.AlertDialog
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.blankii.androidlibrary.exts.loge
import com.blankii.androidlibrary.lib.version.ApkVersionResponseBody
import com.blankii.androidlibrary.lib.version.DownloadFileListener
import com.blankii.androidlibrary.lib.version.DownloadResultListener
import com.blankii.androidlibrary.lib.version.VersionManager
import com.blankii.androidlibrary.lib.version.VersionManager.compareVersions
import com.blankii.androidlibrary.utils.CalcUtil
import com.blankii.androidlibrary.utils.RWUtil.getAppFile
import com.blankii.androidlibrary.utils.RWUtil.getAppVersionName
import com.blankii.androidlibrary.utils.RWUtil.readFileByLines
import com.blankii.androidlibrary.utils.VersionUtils
import com.kstech.ks_gaz01.XML_IS_SINGLE_CONTROL
import com.kstech.ks_gaz01.XML_VERSION
import com.kstech.ks_gaz01.currentCarName
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.databinding.FragmentVersionBinding
import com.kstech.ks_gaz01.getInternalBasePath
import com.kstech.ks_gaz01.socket.SocketFragmentListener
import com.kstech.ks_gaz01.socket.SocketManagerNew


/**
 * author: blankii
 * created on: 2024/5/8 11:15
 * description: 版本管理界面
 * todo 命名不规范
 */
class VersionFragment :
    BaseBindingFragment<FragmentVersionBinding>(FragmentVersionBinding::inflate),
    SocketFragmentListener {
    var controlSize = 0 //车型具有的控制器个数
    var isSingleControl = DebugDataBean.xmlSettings[XML_IS_SINGLE_CONTROL]
    override fun onStop() {
        super.onStop()
        SocketManagerNew.unSubscribeSocketFragmentListener()
    }

    override fun onCreateInit() {

    }

    override fun onInitView() {
        val readTxtBean = readFileByLines(getAppFile())
        binding.apply {
            progressBar.visibility = View.GONE
            lastUseTime.text = "上次登陆时间:${readTxtBean.lastUseTime}"
            useTimeMax.text = "使用截止时间:${readTxtBean.useTimeMax}"
            androidVersion.text = "安卓软件版本:V${getAppVersionName(requireActivity())}"
            checkVersionButton.setOnClickListener {
                startCheckVersion()
            }
        }
        onInitData()
    }

    private fun showAlertDialog(
        projectVersion: String, versionResponseBody: ApkVersionResponseBody
    ) {
        val dialogBuilder = AlertDialog.Builder(requireActivity()).setTitle(
            "当前版本:${projectVersion},最新版本:${
                versionResponseBody.versionShort
            }"
        ).setMessage("更新日志:\r\n${versionResponseBody.changelog}").setPositiveButton(
            "更新版本"
        ) { dialog, which ->
            binding.progressBar.visibility = View.VISIBLE

            VersionManager.downloadApk(
                requireContext(),
                versionResponseBody.installUrl,
                getInternalBasePath(requireContext()),
                "${requireContext().packageName}.apk",
                object : DownloadFileListener {
                    override fun onStart() {

//                        "开始下载".showMsgInfo()
                    }

                    override fun onProgress(progress: Int) {
                        requireActivity().runOnUiThread {
                            binding.progressBar.text = "正在下载:${progress}%"
                        }
                    }

                    override fun onFinish() {
                        requireActivity().runOnUiThread {
                            binding.progressBar.visibility = View.GONE
                        }
                        "下载完成".showSnackBar()
                    }

                    override fun onFail(errorInfo: String) {
                        requireActivity().runOnUiThread {
                            binding.progressBar.visibility = View.GONE
                        }
                        errorInfo.showSnackBar()
                    }

                })
        }.setNegativeButton("取消") { dialog, which ->

        }
        dialogBuilder.show()
    }

    private fun startCheckVersion() {
        VersionManager.download(
            this@VersionFragment, "662dda61f945487e62f7d039", object : DownloadResultListener {
                override fun onStart() {
                    "开始下载".showSnackBar()
                }

                override fun onFinish(versionResponseBody: ApkVersionResponseBody) {
                    requireActivity().runOnUiThread {
                        val localVersion = VersionUtils.getPacketVersionName(requireContext())
                        if (compareVersions(localVersion, versionResponseBody.versionShort)) {
                            showAlertDialog(localVersion, versionResponseBody)
                        } else {
                            "当前版本:V${localVersion}即为最新版本,无需更新".showSnackBar()
                        }
                    }
                }

                override fun onFail(errorInfo: String) {
                    errorInfo.showSnackBar()
                }
            })
    }


//    private fun versionToInt(versionString: String): Int {
//        val arr = versionString.split(".")
//        var result = ""
//        arr.forEach {
//            result += it
//        }
//        return result.toInt()
//
//    }

    private fun onInitData() {
        SocketManagerNew.subscribeSocketFragmentListener(this)
        val version = DebugDataBean.xmlMap[XML_VERSION]
        controlSize = version!!.size
        if (controlSize !in 1..3) {
            throw Exception("控制器版本个数理论上1-3个，请检查控制器配置情况")
        }
        when(controlSize){
            1->{
                binding.t2.text = version.get(0).name
                binding.t1.visibility = View.INVISIBLE
                binding.t4.visibility = View.INVISIBLE
                binding.child4.visibility = View.INVISIBLE
                binding.child5.visibility = View.INVISIBLE
                binding.child6.visibility = View.INVISIBLE
                binding.child7.visibility = View.INVISIBLE
                binding.child8.visibility = View.INVISIBLE
                binding.child9.visibility = View.INVISIBLE
            }
            2->{
                binding.t2.text = version.get(0).name
                binding.t1.text = version.get(1).name
                binding.t4.visibility = View.INVISIBLE
                binding.child7.visibility = View.INVISIBLE
                binding.child8.visibility = View.INVISIBLE
                binding.child9.visibility = View.INVISIBLE
            }
            3->{
                binding.t2.text = version.get(0).name
                binding.t1.text = version.get(1).name
                binding.t4.text = version.get(2).name
            }
        }
        val readBeanList = ArrayList<SocketManagerNew.ReadBean>()

        for (i in version.indices) {
            version[i].childList.forEach {
                readBeanList.add(
                    SocketManagerNew.ReadBean(
                        (it.itemList[0].para0.toInt() - 1).toString(),
                        it.itemList[0].para2,
                        it.itemList.size
                    )
                )
            }
        }
        SocketManagerNew.addReadyLooperList(
            false, readBeanList
        )
    }

    override fun writeSuccess(address: String, value: String) {

    }

    override fun readSuccess(address: String, result: ArrayList<String>) {

        val stringBuilder = StringBuilder()
        result.forEach {
            if (it.length == 4) {
                stringBuilder.append(it.substring(2, 4) + it.substring(0, 2))
            }
        }
        var str = CalcUtil.Hex2CharString(stringBuilder.toString())
        //todo isSingleControl感觉可以去掉呀
        "isSingleControl:$isSingleControl,address$address,value:$str".loge("blankii-test")
        when (controlSize) {
            1 -> {
                //todo 根据xml 的配置去动态设置，不然“通用卷扬”改名字的话就出现bug了
                if (currentCarName.contains("通用卷扬")) {
                    when (address) {
                        "41577" -> {
                            binding.child1.text = "序列号:${str}"
                        }

                        "41583" -> {
                            binding.child2.text = "底层固件:$str"
                        }

                        "41589" -> {
                            binding.child3.text = "应用程序:$str"
                        }
                    }
                } else {
                    when (address) {
                        "41300" -> {
                            binding.child1.text = "序列号:${str}"
                        }

                        "41306" -> {
                            binding.child2.text = "底层固件:$str"
                        }

                        "41312" -> {
                            binding.child3.text = "应用程序:$str"
                        }
                    }
                }
            }

            2 -> {
                when (address) {
                    //双控制器
                    "44650" -> {
                        binding.child1.text = "序列号:${str}"
                    }

                    "44656" -> {
                        binding.child2.text = "底层固件:$str"
                    }

                    "44662" -> {
                        binding.child3.text = "应用程序:$str"
                    }

                    "44669" -> {
                        binding.child4.text = "序列号:$str"
                    }

                    "44675" -> {
                        binding.child5.text = "底层固件:$str"
                    }

                    "44681" -> {
                        binding.child6.text = "应用程序:$str"
                    }
                }
            }

            3 -> {
                when (address) {
                    //三控制器
                    "47000" -> {
                        binding.child1.text = "序列号:${str}"
                    }

                    "47006" -> {
                        binding.child2.text = "底层固件:$str"
                    }

                    "47012" -> {
                        binding.child3.text = "应用程序:$str"
                    }

                    "47019" -> {
                        binding.child4.text = "序列号:$str"
                    }

                    "47025" -> {
                        binding.child5.text = "底层固件:$str"
                    }

                    "47031" -> {
                        binding.child6.text = "应用程序:$str"
                    }

                    "47038" -> {
                        binding.child7.text = "序列号:$str"
                    }

                    "47044" -> {
                        binding.child8.text = "底层固件:$str"
                    }

                    "47050" -> {
                        binding.child9.text = "应用程序:$str"
                    }
                }
            }
        }
    }
}